#!/bin/bash

function get_dist_info()
{
    PLATFORM=`uname -p`
    if [ $PLATFORM = 'unknown' ]; then
       PLATFORM="i386"
    fi
    if [ $PLATFORM = 'i686' ]; then
       PLATFORM="ia64"
    fi
    
    if [ -f /etc/redhat-release ]; then
        DISTRO=`rpm -q --queryformat='%{VERSION}' redhat-release  | awk -F '.' '{ gsub(/[a-zA-Z]+$/, "", $1); print "rhel" $1}'`
    elif   [ -f /etc/suse-release ]; then
        DISTRO=`rpm -q --queryformat='%{VERSION}' sles-release  | awk '{print "sles" $1}'`
    fi
    
    echo "Detected PLATFORM = $PLATFORM, DISTRO = $DISTRO"
}

function get_rpm_list()
{
    base_link=$1
    name_pattern=$2
    
    # Get file name list first
    wget -q $base_link
    cat ./index.html \
        | grep "<A HREF=" \
        | grep $name_pattern \
        | awk -F '"' '{for (i=1;i<=NF;i++) if ($i ~ /^[a-zA-Z0-9].*\.rpm$/) print $i}' \
        | sort -r
    rm -f ./index.html
}

function set_release()
{
    SMX="http://linux.fc.hp.com/manageability/downloads/smx/trunk/releases/"
    TOG="http://linux.fc.hp.com/manageability/downloads/smx/smxtp/"
    MGB="http://linux.fc.hp.com/manageability/downloads/hpmgmtbase/beta/releases/"
}

function set_latest()
{
    SMX="http://linux.fc.hp.com/manageability/downloads/smx/trunk/"
    TOG="http://linux.fc.hp.com/manageability/downloads/smx/smxtp/"
    MGB="http://linux.fc.hp.com/manageability/downloads/hpmgmtbase/beta/"
}


# Main starts here

get_dist_info


if [ $1 = 'release' ]; then
    set_release
else
    set_latest
fi

hpsmx      = `get_rpm_list $SMX "hp-smx-.*\.$DISTRO\.$PLATFORM\.rpm " | grep -v "tests" | head -n 1`
echo $hpsmx
wget $SMX$hpsmx

hpsmxtests = `get_rpm_list $SMX "hp-smx-.*\.$DISTRO\.$PLATFORM\.rpm " | grep "tests" | head -n 1`
echo $hpsmxtests
wget $SMX$hpsmxtests

togpegasus = `get_rpm_list $TOG "tog-pegasus-.*\.$DISTRO\.$PLATFORM\.rpm" | grep -v "devel" | grep -v "oslo" | head -n 1`
echo $togpegasus
wget $TOG$togpegasus

hpmgmtbase = `get_rpm_list $MGB "hpmgmtbase-.*\.$DISTRO\.$PLATFORM\.rpm" | grep -v "devel" | head -n 1`
echo $hpmgmtbase
wget $MGB$hpmgmtbase

wget http://linux.fc.hp.com/~csmith/smx/smx-reqs.tar.gz
tar zxvf smx-reqs.tar.gz 
cd smx-reqs
echo "Installing PyWBEM ......"
sleep 1
# install pywbem
tar zxvf pywbem-*gz
cd pywbem-*
python ./setup.py build
python ./setup.py install
cd ..
cd ..

exit 0

